import Mock from "mockjs"
const Random = require('mockjs').Random;
const data = Mock.mock({
    'userList|55': [
      {
        idd: '@increment',
        name: '@cname()',
        identity: '@id()',
        address: '@city(true)',
        date: '@date(yyyy-MM-dd)',
        image:Random.image('100x100'),
        detail: '@cword(5,10)'
      }
    ]
})
const greateResualt=(status,message,data)=>{
  return {
    status:status?200:500,
    message,
    data,
  }
}
// 处理get请求的url参数
const getQuery = (url, name) => {
  const isFind = url.indexOf(name) !== -1
  if (isFind) {
    const queryArr = url.split('?')[1].split('&')
    for (let i = 0; i < queryArr.length; i++) {
      const result = queryArr[i].split('=')
      if (result[0] === name) {
        return result[1]
      }
    }
  }
  return null
}

Mock.mock(/api\/getData/,"get",() => {
    return greateResualt(true,"列表获取成功",data);
})

Mock.mock(RegExp('mock/userList'), 'get', (options) => {
  // 根据url解析出pageSize的值
 const pageSize = getQuery(options.url, 'pageSize')
   // 根据url解析出currentPage的值
 const currentPage = getQuery(options.url, 'currentPage') 
   // 根据url解析出currentPage的值searchWords
   const searchWords = getQuery(options.url, 'searchWords') 
   const searchKeys = getQuery(options.url, 'searchKeys') 
   const sortKey = getQuery(options.url, 'sortKey') 
   const asc = getQuery(options.url, 'asc') 
 console.log(searchKeys);
//  &sortKey=${sortKey}&asc=${asc}
 let output = [...data.userList];

    // output = search(output, searchWords, JSON.parse(searchKeys));
  console.log(output);
 /**
  * 对返回的数组进行处理 (即实现分页效果)
  * 1.获取起始值  : pageSize=1 currentPage=10 即 0(索引)  
    计算公式 : (pageSize-1)*currentPage
  * 2.获取终止值  : pageSize=1 currentPage=10 即 9(索引)  
    计算公式 : pageSize*currentPage (不-1,是因为使用splice进行截取;)
  * 3.如当前页码超出总页码,则返回 [] ;  
    计算公式 : totalPage=Math.ceil(data.length/currentPage)
  */
 const startIndex = (currentPage - 1) * pageSize
 const endIndex = pageSize * currentPage
 const totalPage = Math.ceil(data.userList.length / pageSize)

 const newDataArr =
   currentPage > totalPage ? [] : data.userList.slice(startIndex, endIndex)

 let result = {
   data: newDataArr,
   totalPage: data.userList.length,
   totalNumber: data.length
 }
 return greateResualt(true,"获取用户列表成功",result);
})
function search(src, searchWords, searchKeys){
  const output= [];
  src.forEach((item) => {
    let isMatched = false;
    for (let i = 0; i < searchKeys.length; i++) {
      console.log(item,searchKeys[i],item[searchKeys[i]]);
      if (item[searchKeys[i]] instanceof Number) {
        item[searchKeys[i]] = item[searchKeys[i]] +"";
      }
      console.log(item[searchKeys[i]]);
      try {
        item[searchKeys[i]].toLowerCase
      } catch (error) {
        console.log(error);
      }
      if (item[searchKeys[i]].toLowerCase?.indexOf(searchWords[0].toLowerCase()) > -1) {
        isMatched = true;
        break;
      }
    }
    if (isMatched) {
      output.push(item);
    }
  });

  return output;
}